package com.heyun.controller;

import com.heyun.constant.Constants;
import com.heyun.entity.pojo.PointsLog;
import com.heyun.entity.vo.*;
import com.heyun.result.Result;
import com.heyun.service.StudentService;
import com.heyun.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;

/**
 * 学生权限
 */
@RestController
@RequestMapping("/student")
@Slf4j
public class StudentController {
    @Autowired
    private StudentService studentService;
    @Autowired
    private ResourceLoader resourceLoader;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    /**
     * 获取课程信息
     * @return
     */
    @GetMapping("/getSubData")
    Result getSubData() {
        SubjectVO[] res = studentService.getSubData();
        if (res.length < 1) {
//            log.info("空信息：" + Arrays.toString(res));
            return Result.error(Constants.GET_SUBJECT_FAILURE);
        }
        log.info(Constants.GET_SUBJECT_SUCCESS + Arrays.toString(res));
        return Result.success(res);
    }

    /**
     * 获取成绩信息
     */
    @GetMapping("/getGrade")
    Result getGrade(String id){
        GradeVO[]  result = studentService.getGrade(id);
        if (result.length < 1){
            return Result.error(Constants.GRADE_FAILURE);
        }
        log.info(Constants.GRADE_SUCCESS+ Arrays.toString(result));
        return Result.success(result);
    }

    /**
     * 获取作业历史记录
     * @return
     */
    @GetMapping("/getExp")
    Result getExp(){
        ExpVO[] result = studentService.getExp();
        if (result.length < 1){
            return Result.error(Constants.GET_HOMEWORK_FAILURE);
        }
        log.info(Constants.GET_HOMEWORK_SUCCESS + Arrays.toString(result));
        return Result.success(result);
    }


    /**
     * 获取学习记录
     * @param id
     * @return
     */
    @DeleteMapping("/delExp")
    Result delExp(String id){
        int num = studentService.delExp(id);
        if (num <1)
            return Result.error(Constants.DELETE_FAILURE);
        else {
            log.info(Constants.DELETE_SUCCESS+": 用户删除 "+num+" 条历史记录");
            return Result.success(num);
        }
    }

    /**
     * 学生端获取自己的平时作业
     */
    @GetMapping("/getHomeworks")
    Result getHomeworks(){
        Homework[] hm = studentService.getHomework();
        if (hm != null)
            return Result.success(hm);
        return Result.error(Constants.GET_HOMEWORK_FAILURE);
    }

    /**
     * 学生获取未完成的签到
     * @return
     */
    @GetMapping("/getSignIn")
    Result getSignIn(){
        SignIn sign = studentService.getSignIn();
        if (sign != null) {
            Map<String, Object> claims = ThreadLocalUtil.get();
            String userId = claims.get("id").toString();
//            studentService.addLog(new PointsLog(userId,"签到",10.0,sign.getSubjectId()));
            return Result.success(sign);
        }
        return Result.error(Constants.GET_SIGN_IN_FAILURE);
    }
    // 文件下载接口
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile(@RequestParam String fileName) {
        try {
            // 获取项目根目录路径
            String rootPath = resourceLoader.getResource("classpath:").getFile().getAbsolutePath();
            // 指定文件夹路径
            String uploadDirPath = rootPath + "/files/";

            // 构建文件路径
            String filePath = uploadDirPath + fileName;
            File file = new File(filePath);

            if (!file.exists()) {
                throw new RuntimeException("文件不存在");
            }

            // 创建Resource对象
            Resource resource = new UrlResource(Paths.get(filePath).toUri());

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");

            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (MalformedURLException e) {
            return ResponseEntity.status(500).body(null);
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }

    /**
     * 获取六个学期的成绩   用于echarts
     * @return
     */
    @GetMapping("/getGrades")
    Result getGrades(){
        return Result.success(studentService.getGrades());
    }

    /**
     * 学生签到
     * @return
     */
    @PutMapping("/signIn")
    Result SignIn(@RequestParam String subjectId) {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String userId = claims.get("id").toString();
        studentService.addLog(new PointsLog(userId,"签到",10.0,subjectId));
        return Result.success(studentService.SignIn(subjectId));
    }
    @GetMapping("/getLogs")
    Result getLogs(){
        return Result.success(studentService.getLogs());
    }

    @GetMapping("/getSignIns")
    Result getSignIns(){
        return Result.success(studentService.getSignIns());
    }
}
